<template>
  <div>
    <UploadExcel
      :onSuccess="onSuccess"
      :before-upload="beforeUpload"
    ></UploadExcel>
  </div>
</template>

<script>
import { addbashuserapi } from '@/api/employes'
export default {
  methods: {
    // 上传文件前校验
    beforeUpload(file) {
      const islt = file.size / 1024 / 1024 < 5
      if (islt) {
        return true
      }
      this.$message({
        message: '请上传5m以内的文件',
        type: 'warning'
      })
      return false
    },
    // 文件上传成功后调用的方法
    async onSuccess({ results, header }) {
      // excel内的数据
      this.tableData = results
      // excel表头
      this.tableHeader = header
      // console.log(header, results)
      if (this.$route.query.type === 'userpeoplebatch') {
        // 员工上传
        this.employesdate(results, header)
      }
      // else if(){

      // }
    },
    // 处理员工上传
    async employesdate(results, header) {
      // 中英对照关系对象
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      const arr = []
      results.forEach((item) => {
        const obj = {}
        for (const key in item) {
          const englishkey = userRelations[key]
          if (englishkey === 'timeOfEntry' || englishkey === 'correctionTime') {
            obj[englishkey] = this.formatExcelDate(item[key], '-')
          } else {
            obj[englishkey] = item[key]
          }
        }

        arr.push(obj)
      })

      await addbashuserapi(arr)
      this.$message.success('批量导入成功')
      this.$router.push('/employees')
    },
    // 处理日期格式
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? '0' + month : month) +
          format +
          (date < 10 ? '0' + date : date)
        )
      }
      return (
        year +
        (month < 10 ? '0' + month : month) +
        (date < 10 ? '0' + date : date)
      )
    }
  }
}
</script>

<style></style>
